// 标准C++头文件
#include <iostream>
#include <vector>
#include <list>
// Linux头文件
#include <sys/stat.h>
#include <sys/socket.h>
#include <net/if.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <net/if.h>
// 三方库头文件
#include "glog/logging.h"
// 用户头文件
#include "capture/interface.h"

using namespace std;

Interface::Interface(string ifName)
{
    this->info.name = ifName;
    GetInterfaceInfo(this->info);
}

// 获取接口名和接口索引
vector<pair<string, unsigned int>> Interface::GetAllInterface()
{
    vector<pair<string, unsigned int>> ifTbl;
    struct if_nameindex *ifni;
    ifni = if_nameindex();
    if(ifni == NULL){
        LOG(INFO) << "get interface name failed" << endl;
        return ifTbl;
    }

    LOG(INFO) << "get all interface: " << endl;
    while(ifni->if_index != 0){
        auto p = make_pair(string(ifni->if_name), ifni->if_index);
        ifTbl.push_back(p);
        ifni++;
        LOG(INFO) << "index: "<< p.second << "    " << "name: " << p.first << endl;
    }

    return ifTbl;
}

bool Interface::exist()
{

    return false;
}
void Interface::GetInterfaceInfo(Info& info)
{
    // 获取IP地址
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if(sock < 0){
        LOG(ERROR) << "open socket failed." << endl;
        return;
    }
    struct ifreq ifreq;
    strcpy(ifreq.ifr_ifrn.ifrn_name, info.name.c_str());
	if (ioctl(sock, SIOCGIFADDR, &ifreq) < 0){
        LOG(ERROR) << "get " << info.name.c_str() << " information failed." << endl;
        return;
    }
    info.address.ip = inet_ntoa(((struct sockaddr_in*)&(ifreq.ifr_addr))->sin_addr);
    LOG(INFO) << info.name.c_str() << " : " << info.address.ip << endl;

    // 获取接口类型

    return;
}